package org.ciallo.simplemusicplayer.activity;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.adapter.SongAdapter;
import org.ciallo.simplemusicplayer.data.model.Song;
import org.ciallo.simplemusicplayer.dialog.SongOptionsDialogFragment;
import org.ciallo.simplemusicplayer.viewmodel.RecentPlayViewModel;
import org.ciallo.simplemusicplayer.viewmodel.SharedViewModel;
import timber.log.Timber;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jukomu
 * @Description: 显示最近播放记录的 Activity
 * @Package: org.ciallo.simplemusicplayer.activity
 * @Project: SimpleMusicPlayer
 * @name: RecentPlayActivity
 * @Date: 2025/5/30-03:07
 * @Filename: RecentPlayActivity
 */
public class RecentPlayActivity extends AppCompatActivity {

    private RecyclerView recyclerViewRecentPlay;
    private SongAdapter songAdapter;
    private RecentPlayViewModel recentPlayViewModel;
    private SharedViewModel sharedViewModel; // 用于播放
    private TextView tvEmptyRecentPlay;
    private MaterialToolbar toolbar;
    private FloatingActionButton fabClearRecentPlay; // 或者使用菜单项

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recent_play);

        toolbar = findViewById(R.id.toolbar_recent_play);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(true); // 显示标题 "最近播放"
        }

        // 初始化ViewModel
        recentPlayViewModel = new ViewModelProvider(this).get(RecentPlayViewModel.class);
        sharedViewModel = new ViewModelProvider(this).get(SharedViewModel.class);

        // 初始化UI
        recyclerViewRecentPlay = findViewById(R.id.recyclerView_recent_play);
        tvEmptyRecentPlay = findViewById(R.id.textView_empty_recent_play);
        fabClearRecentPlay = findViewById(R.id.fab_clear_recent_play);

        setupRecyclerView();
        observeViewModel();

        fabClearRecentPlay.setOnClickListener(v -> showClearConfirmationDialog());
    }

    private void setupRecyclerView() {
        songAdapter = new SongAdapter(
                (song, position) -> { // OnSongClickListener
                    List<Song> currentList = songAdapter.getCurrentList();
                    if (sharedViewModel != null && currentList != null && !currentList.isEmpty()) {
                        sharedViewModel.playSongAtIndex(new ArrayList<>(currentList), position);
                        // 不自动跳转到 PlayerActivity，让用户自己从 MiniPlayer 进入
                    } else {
                        Timber.w("Cannot play song from recent plays: SharedViewModel or list is null/empty.");
                    }
                },
                (song, anchorView) -> { // OnSongOptionsClickListener
                    if (getSupportFragmentManager() != null && song != null) {
                        // 使用 PlayerSongDetailsDialogFragment 或者 SongOptionsDialogFragment
                        // 既然是列表项，SongOptionsDialogFragment 更合适
                        SongOptionsDialogFragment.newInstance(song.getId())
                                .show(getSupportFragmentManager(), SongOptionsDialogFragment.TAG);
                    }
                }
        );
        recyclerViewRecentPlay.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewRecentPlay.setAdapter(songAdapter);
    }

    private void observeViewModel() {
        recentPlayViewModel.getRecentlyPlayedSongs().observe(this, songs -> {
            Timber.d("Recent plays updated. Count: %d", songs != null ? songs.size() : 0);
            if (songs != null && !songs.isEmpty()) {
                songAdapter.submitList(new ArrayList<>(songs));
                tvEmptyRecentPlay.setVisibility(View.GONE);
                recyclerViewRecentPlay.setVisibility(View.VISIBLE);
                fabClearRecentPlay.setVisibility(View.VISIBLE); // 有数据时显示清空按钮
            } else {
                songAdapter.submitList(new ArrayList<>());
                tvEmptyRecentPlay.setVisibility(View.VISIBLE);
                recyclerViewRecentPlay.setVisibility(View.GONE);
                fabClearRecentPlay.setVisibility(View.GONE); // 无数据时隐藏清空按钮
            }
        });
    }

    private void showClearConfirmationDialog() {
        new AlertDialog.Builder(this)
                .setTitle("清空播放记录")
                .setMessage("确定要清空所有最近播放记录吗？")
                .setPositiveButton(R.string.ok, (dialog, which) -> {
                    recentPlayViewModel.clearAllRecentPlays();
                    Toast.makeText(this, "最近播放记录已清空", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed(); // 处理返回按钮
            return true;
        }
        // 如果使用 Toolbar 菜单项来清空，在这里处理
        /*
        if (item.getItemId() == R.id.menu_clear_recent_plays) {
            showClearConfirmationDialog();
            return true;
        }
        */
        return super.onOptionsItemSelected(item);
    }

    // 如果选择使用 Toolbar 菜单项来清空，而不是 FAB
    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_recent_play_menu, menu); // 需要创建此菜单文件
        return true;
    }
    // res/menu/activity_recent_play_menu.xml
    // <menu xmlns:android...> <item android:id="@+id/menu_clear_recent_plays" android:title="清空记录" ... /> </menu>
    */
}